package com.yushu.base.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.yushu.authority.pojo.bo.PmUser;
import com.yushu.authority.pojo.vo.PmUserVO;
import com.yushu.base.mapper.DicSetMapper;
import com.yushu.base.pojo.bo.Dic;
import com.yushu.base.pojo.bo.DicSet;
import com.yushu.base.pojo.vo.DicSetVO;
import com.yushu.base.pojo.vo.DicVO;
import com.yushu.base.service.DicSetService;
import com.yushu.common.execption.CgException;
import com.yushu.common.shiro.ShiroUtil;
import com.yushu.common.util.date.DateUtils;
import com.yushu.common.util.pager.Pages;
import com.yushu.common.util.string.CamelCaseUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 
 * @author test
 * @CreateDate 2020-12-03 15:47:25
 */
@Service("dicSetService")
public class DicSetServiceImpl extends ServiceImpl<DicSetMapper, DicSet> implements DicSetService {
    @Autowired
    private RedisTemplate redisTemplate;

    public Pages<DicSetVO> page(Pages<DicSetVO> page) {
        PmUser sessionUser = ShiroUtil.getSessionUser();
        EntityWrapper wrapper = new EntityWrapper<DicSetVO>();
        DicSetVO dicSet = page.getData();
        if (null != dicSet) {
            if (StringUtils.isNotEmpty(dicSet.getId())) {
                wrapper.like("t.id", dicSet.getId(), SqlLike.DEFAULT);
            }
            if (null != dicSet.getCreateTimeBefore() && null != dicSet.getCreateTimeAfter()) {
                String dateBefore = DateUtils.dateToString(dicSet.getCreateTimeBefore());
                String dateAfter = DateUtils.dateToString(dicSet.getCreateTimeAfter());
                wrapper.between("t.create_time", dateBefore, dateAfter);
            }
            if (StringUtils.isNotEmpty(dicSet.getName())) {
                wrapper.like("t.name", dicSet.getName(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(dicSet.getOrgId())) {
                wrapper.like("t.org_id", dicSet.getOrgId(), SqlLike.DEFAULT);
            }
            if (null != dicSet.getUpdateTimeBefore() && null != dicSet.getUpdateTimeAfter()) {
                String dateBefore = DateUtils.dateToString(dicSet.getUpdateTimeBefore());
                String dateAfter = DateUtils.dateToString(dicSet.getUpdateTimeAfter());
                wrapper.between("t.update_time", dateBefore, dateAfter);
            }
            if (StringUtils.isNotEmpty(dicSet.getPid())) {
                wrapper.like("t.pid", dicSet.getPid(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(dicSet.getStatus())) {
                wrapper.like("t.status", dicSet.getStatus(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(dicSet.getUserId())) {
                wrapper.like("t.user_id", dicSet.getUserId(), SqlLike.DEFAULT);
            }

            if (StringUtils.isNotEmpty(dicSet.getUpdateUserId())) {
                wrapper.like("t.update_user_id", dicSet.getUpdateUserId(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(dicSet.getSetCode())) {
                wrapper.like("t.set_code", dicSet.getSetCode(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(dicSet.getDicCode())) {
                wrapper.like("t.dic_code", dicSet.getDicCode(), SqlLike.DEFAULT);
            }
            if (StringUtils.isNotEmpty(page.getSort())) {
                wrapper.orderBy(CamelCaseUtil.toUnderlineName(page.getSort()), "asc".equals(page.getOrder()) ? true : false);
            }
        }
        List<DicSetVO> list = baseMapper.selectPageList(page, wrapper);
        page.setRecords(list);
        return page;
    }


    /**
     * 删除的时候同步字典集的缓存数据
     *
     * @param id 主键
     * @return
     */
    //@CacheEvict(value = "dicSet", key = "#id")
    @Override
    public boolean deleteById(Serializable id) {
        return super.deleteById(id);
    }


    /**
     * 批量删除字典集
     *
     * @param dicSets
     * @return
     */
    public boolean deleteBatch(List<DicVO> dics, List<DicSet> dicSets) throws CgException {
        boolean deleteState = true;
        List<String> ids = new ArrayList<String>();
        PmUser sessionUser = ShiroUtil.getSessionUser();
        if (CollectionUtils.isNotEmpty(dics)) {
            for (Dic dic : dics) {
                EntityWrapper wrapper = new EntityWrapper<DicSet>();
                wrapper.eq("dic_code", dic.getCode());

                baseMapper.delete(wrapper);
            }

        }

        return deleteState;
    }


    @Override
    public void deleteBatch(List<DicSet> dicSets) {
        if (CollectionUtils.isNotEmpty(dicSets)) {
            DicSet dicSet = dicSets.get(0);
            EntityWrapper wrapper = new EntityWrapper<DicSet>();
            wrapper.eq("dic_code", dicSet.getDicCode());
             baseMapper.delete(wrapper);
        }
    }

    /**
     * 通过主键更新字典集的缓存数据
     *
     * @param dicSet
     * @return
     */
    //@CachePut(value = "dicSet", key = "#dicSet.id")
    public DicSet updateByKey(DicSet dicSet) throws CgException {
        try {
            PmUser sessionUser = ShiroUtil.getSessionUser();
            dicSet.setUpdateTime(new Date());
            dicSet.setUpdateUserId(sessionUser.getId());
            super.updateById(dicSet);
        } catch (RuntimeException e) {
            throw new CgException(e.getMessage());
        }
        return dicSet;
    }

    /**
     * 保存的时候清除所有字典集的缓存数据
     *
     * @param dicSet
     * @return
     */
    //@CacheEvict(value = "dicSet",allEntries=true)
    @Override
    public boolean insert(DicSet dicSet) throws CgException {
        try {
            PmUser sessionUser = ShiroUtil.getSessionUser();
            PmUserVO userCache = (PmUserVO) redisTemplate.opsForValue().get("userSession_" + sessionUser.getId());
            dicSet.setUserId(userCache.getId());
            dicSet.setCreateTime(new Date());
            dicSet.setOrgId(sessionUser.getOrgId());
            dicSet.setId(IdWorker.get32UUID());
            return super.insert(dicSet);
        } catch (RuntimeException e) {
            throw new CgException(e.getMessage());
        }
    }


    /**
     * 查询时保存字典集的缓存数据
     *
     * @param id 主键
     * @return
     */
    //@Cacheable(value = "dicSet", key = "#id")
    @Override
    public DicSet selectById(Serializable id) {
        return super.selectById(id);
    }

    @Override
    public String checkRepeat(Map map) {
        String name = map.get("name") + "";
        String value = map.get("value") + "";
        String key = map.get("key") + "";
        int count = baseMapper.queryCountByName(map);
//        如果key存在，则是修改，否则是新增
        if (StringUtils.isNotBlank(key)) {
            /*如果是更新，则数字可以大于1*/
            if (count <= 0) {
                return "true";
            } else if (count > 1) {//说明存在多个
                return "false";
            } else if (count == 1) {

                EntityWrapper wrapper = new EntityWrapper<DicSet>();
                wrapper.eq(name, value);
                List<DicSet> dicSets = baseMapper.selectList(wrapper);
                String checkExit = "true";
                if (CollectionUtils.isNotEmpty(dicSets)) {
                    for (int i = 0; i < dicSets.size(); i++) {
                        DicSet dicSet = dicSets.get(i);
//                        说明当前值象存在于不同的对象之中，也不能重复
                        if (!StringUtils.equals(dicSet.getId().trim(), key.trim())) {
                            checkExit = "false";
                        }
                    }
                }
                return checkExit;
            } else {
                return "true";
            }
        } else {
            /*如果是新增，则数字可以大于0*/
            if (count > 0) {
                return "false";
            } else {
                return "true";
            }
        }
    }

    @Override
    public List<DicSet> selectList(DicSet dicSet) {
        EntityWrapper wrapper = new EntityWrapper<DicSet>();
        if (StringUtils.isNotEmpty(dicSet.getId())) {
            wrapper.eq("id", dicSet.getId());
        }

        if (StringUtils.isNotEmpty(dicSet.getName())) {
            wrapper.eq("name", dicSet.getName());
        }
        if (StringUtils.isNotEmpty(dicSet.getOrgId())) {
            wrapper.eq("org_id", dicSet.getOrgId());
        }

        if (StringUtils.isNotEmpty(dicSet.getPid())) {
            wrapper.eq("pid", dicSet.getPid());
        }
        if (StringUtils.isNotEmpty(dicSet.getStatus())) {
            wrapper.eq("status", dicSet.getStatus());
        }
        if (StringUtils.isNotEmpty(dicSet.getUserId())) {
            wrapper.eq("user_id", dicSet.getUserId());
        }

        if (StringUtils.isNotEmpty(dicSet.getUpdateUserId())) {
            wrapper.eq("update_user_id", dicSet.getUpdateUserId());
        }
        if (StringUtils.isNotEmpty(dicSet.getSetCode())) {
            wrapper.eq("set_code", dicSet.getSetCode());
        }
        if (StringUtils.isNotEmpty(dicSet.getDicCode())) {
            wrapper.eq("dic_code", dicSet.getDicCode());
        }
        List<DicSet> list = selectList(wrapper);
        return list;
    }

    @Override
    public List<DicSet> selectDicSetList(String dicId) {
        EntityWrapper wrapper = new EntityWrapper<DicSetVO>();
        wrapper.eq("dic_code", dicId);
        List<DicSet> list = baseMapper.selectList(wrapper);
        return list;
    }

    @Override
    public boolean insertBatch(DicVO dic, List<DicSet> dicSets) {
        try {
            PmUser sessionUser = ShiroUtil.getSessionUser();

            if (CollectionUtils.isNotEmpty(dicSets)) {


                EntityWrapper wrapper = new EntityWrapper<DicSet>();
                wrapper.eq("dic_code", dic.getCode());
                wrapper.setSqlSelect("cast(max(set_code +'') as signed integer) id");

                Object o = selectObj(wrapper);
                String states = "";
                if (null == o) {
                    EntityWrapper wrapper2 = new EntityWrapper<DicSet>();
                    wrapper2.setSqlSelect("cast(max(set_code +'') as signed integer) id");
                    o = selectObj(wrapper2);
                    if (null == o) {
                        o = "0";
                        states = "new";
                    } else {
                        states = "old";
                    }
                } else {
                    states = "old";
                }


                for (int i = 0; i < dicSets.size(); i++) {
//                    int max = Integer.parseInt(o.toString()) + (1 + i);
                    //TODO 前补零方法一
                    DecimalFormat g1 = new DecimalFormat("000000");
                    String code = g1.format(0 + i);

                    DicSet dicSet = dicSets.get(i);
                    dicSet.setUserId(sessionUser.getId());
                    dicSet.setCreateTime(new Date());
                    dicSet.setOrgId(sessionUser.getOrgId());
                    dicSet.setId(IdWorker.get32UUID());
                    dicSet.setSetCode(dic.getCode() + (code));
                    dicSet.setDicCode(dic.getCode());
                    dicSet.setPid("-1");
                }
                for (DicSet dicSet : dicSets) {

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.insertBatch(dicSets);
    }

}
